package com.practice.communication.nio.gp.channel;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileChannelDemo {
	
	public static void main(String[] args){
		File file = null;
		try {
			file = new File("F:\\nio_utf8.data");
			if (!file.exists())
				file.createNewFile();
			
			//根据文件输出流创建与这个文件相关的通道
			FileOutputStream out = new FileOutputStream(file);
			FileChannel channel = out.getChannel();
			
			//向ByteBuffer中放入字符串UTF-8的字节，position=17，limit=64
			ByteBuffer byteBuffer = ByteBuffer.allocate(64);
			byteBuffer.put("Hello,World 123 \n".getBytes("UTF-8"));
			
			//flip方法，position=0, limie=17
			byteBuffer.flip();
			
			//write方法使得ByteBuffer的position到limit中的元素写入通道
			channel.write(byteBuffer);
			
			//clear方法使得position=0,limit=64
			byteBuffer.clear();
			
			byteBuffer.put("你好，世界 456".getBytes("UTF-8"));
			byteBuffer.flip();
			
			channel.write(byteBuffer);
			byteBuffer.clear();
			
			out.close();
			channel.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		//从刚才的文件中读取字符序列
		try {
			//通过Path对象创建文件通道
			Path path = Paths.get("F:\\nio_utf8.data");
			FileChannel channel = FileChannel.open(path);
			
			ByteBuffer byteBuffer  = ByteBuffer.allocate((int)channel.size() +1);
			
			Charset utf8 = Charset.forName("UTF-8");
			
			//阻塞模式，读取完才能返回
			channel.read(byteBuffer);
			
			byteBuffer.flip();
			CharBuffer charBuffer = utf8.decode(byteBuffer);
			System.out.println(charBuffer.toString());
			
			byteBuffer.clear();
			
			channel.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (file.exists())
				file.delete();
		}
	}

}
